﻿/*
 * Created by SharpDevelop.
 * User: Matjaž
 * Date: 21.11.2008
 * Time: 20:14
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

using Microsoft.Win32;

namespace gopher
{
	/// <summary>
	/// Description of Settings.
	/// </summary>
	public partial class SettingsDialog : Form
	{
		private DataSet ds;
		private string settingsFile;
		private string settingsDir;
		private string favouritesFile;
		public SettingsDialog()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		void SettingsLoad(object sender, EventArgs e)
		{
			button1.Enabled = true;
			ds = new DataSet();
			RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
			settingsDir = key.GetValue("AppData").ToString()+"\\Gopher\\";
			//settingsFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)+"\\settings.xml";
			//settingsFile = settingsDir+"\\settings.xml";
			settingsFile = key.GetValue("AppData").ToString()+"\\Gopher\\settings.xml";
			favouritesFile = key.GetValue("AppData").ToString()+"\\Gopher\\favourites.xml";
			/*
			settingsDir = "/Users/matjaz/mGopher/settings/";
			favouritesFile ="/Users/matjaz/mGopher/settings/favourites.xml";
			settingsFile = "/Users/matjaz/mGopher/settings/settings.xml";
			*/
//			settingsFile = Assembly.GetExecutingAssembly().Location;
//			settingsFile = settingsFile.Substring(0,settingsFile.LastIndexOf("\\"));
//			settingsFile = settingsFile+"\\settings.xml";	                                      
			try
			{
				ds.ReadXml(settingsFile);
				DataRow dr = ds.Tables[0].Rows[0];
				serverBox.Text = dr["server"].ToString();
				selectorBox.Text = dr["selector"].ToString();
				portBox.Text = dr["port"].ToString();
				timeoutBox.Text = dr["timeout"].ToString();
				folderBox.Text = dr["downloads"].ToString();
				searchServerBox.Text = dr["searchServer"].ToString();
				searchSelectorBox.Text = dr["searchSelector"].ToString();
				searchPortBox.Text = dr["searchPort"].ToString();
				sizeWarningBox.Text = dr["plusFileSizeWarning"].ToString();
			}
			catch(Exception)
			{
				//MessageBox.Show("Error reading program settings (settings.xml)\n\n"+e1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				timeoutBox.Text = "500";
				portBox.Text = "70";
			}
		}
		
		private void saveSettings()
		{
			ds.Tables[0].Rows[0]["server"] = serverBox.Text;
			ds.Tables[0].Rows[0]["selector"] = selectorBox.Text;
			ds.Tables[0].Rows[0]["port"] = portBox.Text;
			ds.Tables[0].Rows[0]["timeout"] = timeoutBox.Text;
			ds.Tables[0].Rows[0]["downloads"] = folderBox.Text;
			ds.Tables[0].Rows[0]["searchServer"] = searchServerBox.Text;
			ds.Tables[0].Rows[0]["searchSelector"] = searchSelectorBox.Text;
			ds.Tables[0].Rows[0]["searchPort"] = searchPortBox.Text;
			ds.Tables[0].Rows[0]["plusFileSizeWarning"] = sizeWarningBox.Text;
			ds.WriteXml(settingsFile, XmlWriteMode.WriteSchema);
		}
		
		void saveFavourites()
		{
			FileSystemInfo si3 = new FileInfo(favouritesFile);
			FileSystemInfo si2 = new DirectoryInfo(settingsDir);
			
			if(si2.Exists == false)
			{
				System.IO.Directory.CreateDirectory(settingsDir);
			}
			if(si3.Exists)
			{
				if(si3.Attributes != FileAttributes.Normal)
				{
					si3.Attributes = FileAttributes.Normal;
				}
			}
			else
			{
				StreamWriter sw = new StreamWriter(favouritesFile);
				sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
				sw.WriteLine("<favourites>");
				sw.WriteLine("  <item name=\"Floodgap\" type=\"0\" server=\"gopher.floodgap.com\" port=\"70\" selector=\"\" plus=\"\" />");
				sw.WriteLine("</favourites>");
				sw.Close();
			}
		}
		
		void SaveButtonClick(object sender, EventArgs e)
		{
			//DataSet ds = new DataSet();
			try
			{
				saveSettings();
			}
			catch(Exception)
			{
				//MessageBox.Show("Error saving program settings (settings.xml)\n\n"+e2.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
				
				FileSystemInfo si = new FileInfo(settingsFile);
				FileSystemInfo si2 = new DirectoryInfo(settingsDir);
				try
				{
					if(si2.Exists == false)
					{
						System.IO.Directory.CreateDirectory(settingsDir);
					}
					if(si.Exists)
					{
						if(si.Attributes != FileAttributes.Normal)
						{
							si.Attributes = FileAttributes.Normal;
							try
							{
								saveSettings();
							}
							catch(Exception e4)
							{
								MessageBox.Show("Error saving program settings (settings.xml)\n\n"+e4.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
							}
						}
					}
					else
					{
						StreamWriter sw = new StreamWriter(settingsFile);
						sw.WriteLine("<?xml version=\"1.0\" standalone=\"yes\"?>");
						sw.WriteLine("<Settings>");
						sw.WriteLine("\t<root>");
						sw.Write("\t\t<server>");
						sw.Write(serverBox.Text);
						sw.WriteLine("</server>");
						sw.Write("\t\t<selector>");
						sw.Write(selectorBox.Text);
						sw.WriteLine("</selector>");
						sw.Write("\t\t<port>");
						sw.Write(portBox.Text);
						sw.WriteLine("</port>");
						sw.Write("\t\t<timeout>");
						sw.Write(timeoutBox.Text);
						sw.WriteLine("</timeout>");
						sw.Write("\t\t<downloads>");
						sw.Write(folderBox.Text);
						sw.WriteLine("</downloads>");
						sw.Write("\t\t<searchServer>");
						sw.Write(searchServerBox.Text);
						sw.WriteLine("</searchServer>");
						sw.Write("\t\t<searchSelector>");
						sw.Write(searchSelectorBox.Text);
						sw.WriteLine("</searchSelector>");
						sw.Write("\t\t<searchPort>");
						sw.Write(searchPortBox.Text);
						sw.WriteLine("</searchPort>");
						sw.WriteLine("<plusOn>on</plusOn>");
						sw.WriteLine("<plusRefreshOn>on</plusRefreshOn>");
						sw.WriteLine("<plusFileSizeWarning>1</plusFileSizeWarning>");
						sw.WriteLine("\t</root>");
						sw.WriteLine("</Settings>");
						sw.Close();
					}
					
				}
				catch(Exception e3)
				{
					MessageBox.Show("Error saving file\n\n"+e3.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			Close();
		}
		
		void CancelButtonClick(object sender, EventArgs e)
		{
			Close();
		}
		
		void SettingsHelpRequested(object sender, HelpEventArgs hlpevent)
		{
			Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher.chm", "html\\settings-dialog.htm");
		}
		
		void BrowseButtonClick(object sender, EventArgs e)
		{
			FolderBrowserDialog dlg = new FolderBrowserDialog();
			dlg.Description = "Select a folder to which the file will be saved.";
			dlg.RootFolder = Environment.SpecialFolder.MyComputer;
			if(dlg.ShowDialog() == DialogResult.OK)
			{
				folderBox.Text = dlg.SelectedPath;
			}
		}
		
		void Button1Click(object sender, EventArgs e)
		{
			saveFavourites();
			button1.Enabled = false;
		}
	}
}
